/**
 * Project Name:mauto-web
 * File Name:AreaService.java
 * Package Name:com.inftech.mauto.sys.service
 * Date:2016年10月7日下午9:14:13
 * Copyright (c) 2016, inf-technology Co., Ltd. All Rights Reserved.
 *
*/

package com.inftech.mauto.core.service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.inftech.mauto.common.base.BusinessException;
import com.inftech.mauto.common.constant.BusinessConstant;
import com.inftech.mauto.common.constant.HttpStatusCodeEnum;
import com.inftech.mauto.common.utils.CommonUtils;
import com.inftech.mauto.common.utils.NewImageUtils;
import com.inftech.mauto.core.dao.IActivityConditionDao;
import com.inftech.mauto.core.entity.ActivityCondition;
import com.inftech.mauto.sys.dao.IDeliveryInfoDao;
import com.inftech.mauto.sys.dao.IFileDao;
import com.inftech.mauto.sys.entity.DeliveryInfo;
import com.inftech.mauto.sys.entity.File;
import com.mingsoft.base.biz.impl.BaseBizImpl;
import com.mingsoft.base.dao.IBaseDao;
import com.mingsoft.weixin.dao.IWeixinDao;
import com.mingsoft.weixin.dao.IWeixinPeopleDao;
import com.mingsoft.weixin.entity.WeixinEntity;
import com.mingsoft.weixin.entity.WeixinPeopleEntity;
import com.mingsoft.weixin.util.MessageUtils;
import com.mingsoft.weixin.util.QrcodeUtils;
import com.mingsoft.weixin.util.UploadDownUtils;

/**
 * 
 * ClassName: ActivityConditionService <br/>
 * Function: 活动情况service. <br/>
 * date: 2016年11月6日 下午10:24:00 <br/>
 *
 * @author puyf
 * @version
 * @since JDK 1.7
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
@Service("activityConditionService")
public class ActivityConditionService extends BaseBizImpl {

	/**
	 * 文件持久化层注入
	 */
	@Autowired
	private IFileDao fileDao;

	/**
	 * 注入微信持久化层
	 */
	@Autowired
	private IWeixinDao weixinDao;

	/**
	 * 注入微信用户持久化层
	 */
	@Autowired
	private IWeixinPeopleDao weixinPeopleDao;

	/**
	 * 注入活动情况持久化层
	 */
	@Autowired
	private IActivityConditionDao activityConditionDao;

	/**
	 * 收货信息持久化层
	 */
	@Autowired
	private IDeliveryInfoDao deliveryInfoDao;

	/**
	 * 文件路径
	 */
	@Value("${filePath}")
	private String filePath;

	/**
	 * 后台服务器地址
	 */
	@Value("${adminUrl}")
	private String adminUrl;

	/**
	 * 活动详情地址
	 */
	@Value("${activityCondUrl}")
	private String activityCondUrl;

	@Override
	protected IBaseDao getDao() {
		return activityConditionDao;
	}

	/**
	 * 
	 * saveQrcode:生成带参数二维码 . <br/>
	 *
	 * @author puyf
	 * @param peopleId
	 * @throws Exception
	 * @since JDK 1.7
	 */
	public void saveQrcode(WeixinPeopleEntity people) throws Exception {
		int peopleId = people.getPeopleId();
		String openId = people.getWeixinPeopleOpenId();
		String headimgUrl = people.getWeixinPeopleHeadimgUrl();
		// 获取微信信息
		WeixinEntity weixin = weixinDao.getEntity(null, null, null);
		// 查询该用户是否已生成带参数二维码
		Map<String, Object> whereMap = new HashMap<String, Object>();
		whereMap.put("object_id", peopleId);
		whereMap.put("object_type", BusinessConstant.FILE_TYPE_QRCODE_IMG);
		whereMap.put("del_flag", 0);
		File qrcode = fileDao.getEntity(whereMap);
		// 二维码图片
		String qrcodePath = filePath + "qrcode/" + peopleId + ".png";
		if (qrcode == null) {
			// 未生成二维码，生成二维码
			java.io.File saveDirFile = new java.io.File(filePath + "qrcode");
			if (!saveDirFile.exists()) {
				saveDirFile.mkdirs();
			}
			QrcodeUtils qrcodeUtils = new QrcodeUtils(weixin.getWeixinAppID(), weixin.getWeixinAppSecret());
			Map<String, Object> resultMap = qrcodeUtils.createLimitQrcode(qrcodePath, peopleId);
			if ((boolean) resultMap.get(QrcodeUtils.MAP_TYPE)) {
				// 创建成功，组合图片
				NewImageUtils.watermark(adminUrl + "files/qrcode/bottom.png", qrcodePath, headimgUrl);
				// 插入文件表
				Date now = CommonUtils.getNowD();
				File file = new File();
				file.setObjectId(Integer.valueOf(peopleId));
				file.setObjectType(BusinessConstant.FILE_TYPE_QRCODE_IMG);
				file.setFilePath("qrcode/" + peopleId + ".png");
				file.setCreateBy(peopleId);
				file.setCreateDate(now);
				file.setUpdateDate(now);
				file.setDelFlag(0);
				fileDao.saveEntity(file);
			} else {
				throw new BusinessException(HttpStatusCodeEnum.STATUS_CODE_954);
			}
		}
		// 将二维码图片上传
		UploadDownUtils uploadDownUtils = new UploadDownUtils(weixin.getWeixinAppID(), weixin.getWeixinAppSecret());
		String mediaId = UploadDownUtils.uploadMedia(uploadDownUtils.getAccessToken(), "image", qrcodePath);
		// 发送客服消息
		MessageUtils messageUtils = new MessageUtils(weixin.getWeixinAppID(), weixin.getWeixinAppSecret());
		messageUtils.sendImageToUser(openId, mediaId);
		LOG.info("向openId" + openId + "推送二维码图片成功");
	}

	/**
	 * 
	 * modifyActivityCondSubsNum:修改关注人数. <br/>
	 *
	 * @author puyf
	 * @throws Exception
	 * @since JDK 1.7
	 */
	public void modifyActivityCondSubsNum(Integer peopleId, String fromOpenId) throws Exception {
		// 判断该次关注的人之前是否已关注过
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("openId", fromOpenId);
		WeixinPeopleEntity weixinPeopleFrom = weixinPeopleDao.getWeixinPeopleEntity(paramMap);
		if (weixinPeopleFrom != null) {
			// 之前已关注的不处理
			return;
		}
		paramMap.clear();
		paramMap.put("activity_id", BusinessConstant.ACTIVITY_TQ);
		paramMap.put("people_id", peopleId);
		paramMap.put("del_flag", 0);
		ActivityCondition activityCondition = activityConditionDao.getEntity(paramMap);
		Date now = CommonUtils.getNowD();
		if (activityCondition == null) {
			// 之前未拉到人，插入活动记录
			activityCondition = new ActivityCondition();
			activityCondition.setActivityId(BusinessConstant.ACTIVITY_TQ);
			activityCondition.setPeopleId(peopleId);
			activityCondition.setActivityCondGet(BusinessConstant.ACTIVITY_NOT_GET);
			activityCondition.setActivityCondWin(BusinessConstant.ACTIVITY_NOT_WIN);
			activityCondition.setActivityCondSubsNum(1);
			// activityCondition.setCreateBy(peopleId);
			activityCondition.setCreateDate(now);
			activityCondition.setUpdateDate(now);
			activityCondition.setDelFlag(0);
			activityConditionDao.saveEntity(activityCondition);
		} else {
			// 之前有拉到人，更新活动记录
			// 已关注人数
			int subsNum = activityCondition.getActivityCondSubsNum();
			if (subsNum == BusinessConstant.ACTIVITY_WIN_NUM - 1) {
				// 关注人数达到中奖要求
				// 设置该人员中奖
				activityCondition.setActivityCondWin(BusinessConstant.ACTIVITY_WIN);
				// 发送客服消息通知前往领奖
				Map<String, Object> requestMap = new HashMap<String, Object>();
				requestMap.put("peopleId", peopleId);
				WeixinPeopleEntity weixinPeople = weixinPeopleDao.getWeixinPeopleEntity(requestMap);
				String openId = weixinPeople.getWeixinPeopleOpenId();
				String content = "恭喜您完成踏青助力推荐加关注任务，快来领取奖品吧！<a href='" + activityCondUrl + "'>点击领奖</a>";
				// 获取微信信息
				WeixinEntity weixin = weixinDao.getEntity(null, null, null);
				MessageUtils messageUtils = new MessageUtils(weixin.getWeixinAppID(), weixin.getWeixinAppSecret());
				messageUtils.sendTextToUser(openId, content);
				LOG.info("向openId" + openId + "推送领奖链接成功");
			}
			activityCondition.setActivityCondSubsNum(subsNum + 1);
			activityCondition.setUpdateDate(now);
			activityConditionDao.updateEntity(activityCondition);
		}
	}

	/**
	 * 
	 * queryActivityCondition:查询活动情况. <br/>
	 *
	 * @author puyf
	 * @param paramMap
	 * @return
	 * @throws Exception
	 * @since JDK 1.7
	 */
	public Map<String, Object> queryActivityCondition(Map<String, Object> paramMap) throws Exception {
		paramMap.put("del_flag", 0);
		// 查询参与情况
		ActivityCondition activityCondition = activityConditionDao.getEntity(paramMap);
		Map<String, Object> resultMap = new HashMap<String, Object>();
		// 查询剩余奖品数
		paramMap.remove("people_id");
		paramMap.put("activity_cond_get", BusinessConstant.ACTIVITY_GET);
		int getNum = activityConditionDao.queryGetCount(paramMap);
		int getNumRest = BusinessConstant.ACTIVITY_PRIZE_QUOTA - getNum >= 0
				? BusinessConstant.ACTIVITY_PRIZE_QUOTA - getNum : 0;
		// 剩余奖品数
		resultMap.put("activityGetNumRest", getNumRest);

		if (activityCondition == null) {
			// 拉关注人数
			resultMap.put("activityCondSubsNum", 0);
			// 剩余人数
			resultMap.put("activityCondSubsNumRest", BusinessConstant.ACTIVITY_WIN_NUM);
			// 中奖状态
			resultMap.put("activityCondWin", BusinessConstant.ACTIVITY_NOT_WIN);
			// 领取状态
			resultMap.put("activityCondGet", BusinessConstant.ACTIVITY_NOT_GET);
		} else {
			// 活动情况id
			resultMap.put("activityCondId", activityCondition.getId());
			// 拉关注人数
			resultMap.put("activityCondSubsNum", activityCondition.getActivityCondSubsNum());
			// 剩余人数
			int activityCondSubsNumRest = BusinessConstant.ACTIVITY_WIN_NUM
					- activityCondition.getActivityCondSubsNum() >= 0
							? BusinessConstant.ACTIVITY_WIN_NUM - activityCondition.getActivityCondSubsNum() : 0;
			resultMap.put("activityCondSubsNumRest", activityCondSubsNumRest);
			// 中奖状态
			resultMap.put("activityCondWin", activityCondition.getActivityCondWin());
			// 领取状态
			resultMap.put("activityCondGet", activityCondition.getActivityCondGet());
		}
		return resultMap;
	}

	/**
	 * 
	 * receivePrize:领奖. <br/>
	 *
	 * @author puyf
	 * @param paramMap
	 * @throws Exception
	 * @since JDK 1.7
	 */
	public void modifyActivityConditionReceive(Map<String, Object> paramMap) throws Exception {
		// 插入收货地址
		DeliveryInfo deliveryInfo = new DeliveryInfo();
		int peopleId = (Integer) paramMap.get("peopleId");
		Date now = CommonUtils.getNowD();
		deliveryInfo.setPeopleId(peopleId);
		deliveryInfo.setDeliveryContact((String) paramMap.get("deliveryContact"));
		deliveryInfo.setDeliveryContactPhone((String) paramMap.get("deliveryContactPhone"));
		deliveryInfo.setDeliveryAddress((String) paramMap.get("deliveryAddress"));
		deliveryInfo.setCreateBy(peopleId);
		deliveryInfo.setCreateDate(now);
		deliveryInfo.setUpdateDate(now);
		deliveryInfo.setDelFlag(0);
		deliveryInfoDao.saveEntity(deliveryInfo);
		// 活动情况id
		int activityConditionId = (Integer) paramMap.get("activityCondId");
		paramMap.clear();
		paramMap.put("id", activityConditionId);
		paramMap.put("del_flag", 0);
		ActivityCondition activityCondition = activityConditionDao.getEntity(paramMap);
		// 判断是否中奖
		if (!BusinessConstant.ACTIVITY_WIN.equals(activityCondition.getActivityCondWin())) {
			throw new BusinessException(HttpStatusCodeEnum.STATUS_CODE_951);
		}
		// 判断是否已领过奖
		if (BusinessConstant.ACTIVITY_GET.equals(activityCondition.getActivityCondGet())) {
			throw new BusinessException(HttpStatusCodeEnum.STATUS_CODE_952);
		}
		// 判断奖品是否有剩余
		paramMap.remove("id");
		paramMap.put("activity_cond_get", BusinessConstant.ACTIVITY_GET);
		int getNum = activityConditionDao.queryGetCount(paramMap);
		int getNumRest = BusinessConstant.ACTIVITY_PRIZE_QUOTA - getNum;
		if (getNumRest <= 0) {
			throw new BusinessException(HttpStatusCodeEnum.STATUS_CODE_953);
		}
		// 更新活动情况
		activityCondition = new ActivityCondition();
		activityCondition.setId(String.valueOf(activityConditionId));
		activityCondition.setActivityCondGet(BusinessConstant.ACTIVITY_GET);
		activityCondition.setUpdateBy(peopleId);
		activityCondition.setUpdateDate(now);
		activityConditionDao.updateEntity(activityCondition);
	}
}
